﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PINDialog.xaml.cs" company="Mar3ek">
//   This code is licensed under the Mozilla Public License 2.0.
//   You can find the full license text at the following address:
//   https://winkee.codeplex.com/license
// </copyright>
// <summary>
//   Defines the PINDialog type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WinKee.Dialogs
{
    using Windows.Storage;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public sealed partial class PINDialog
    {
        /// <summary>
        /// The number of incorrect password attempts.
        /// </summary>
        private int incorrectAttempts;

        /// <summary>
        /// Initializes a new instance of the <see cref="PINDialog"/> class.
        /// </summary>
        public PINDialog()
        {
            this.InitializeComponent();
        }

        private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            if (string.IsNullOrEmpty(this.password.Password))
            {
                args.Cancel = true;
                return;
            }

            if (PasswordSecurity.VerifyAppPassword(
                this.password.Password,
                (string)ApplicationData.Current.LocalSettings.Values[Definitions.PinContentKey]))
            {
                return;
            }

            args.Cancel = true;

            this.incorrectAttempts++;
            this.RemainingAttemptsTextBlock.Text = (3 - this.incorrectAttempts).ToString();

            if (this.incorrectAttempts < 3)
            {
                return;
            }

            this.incorrectAttempts = 0;
            Application.Current.Exit();
        }

        private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
        }

        /// <summary>
        /// Gets the password.
        /// </summary>
        internal string Password
        {
            get
            {
                return this.password.Password;
            }
        }

        private void ContentDialog_Opened(ContentDialog sender, ContentDialogOpenedEventArgs args)
        {
            this.password.Focus(FocusState.Keyboard);
        }
    }
}
